package com.csoa.community.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.csoa.community.R;
import com.csoa.community.bean.LinkmanModel;
import com.csoa.community.net.WcfAsyncTask;
import com.csoa.community.requests.AbstractRequest;
import com.csoa.community.requests.LinkmanRequest;
import com.csoa.community.utils.StringUtils;
import com.csoa.community.widget.PullToRefreshBase.OnRefreshListener;
import com.csoa.community.widget.PullToRefreshListView;

public class LinkmanActivity extends BaseActivity implements OnClickListener {
	PullToRefreshListView mPullList;
	ListView mList;
	ProgressBar mProgress;
	EditText mEdit;
	RadioGroup mRadio;

	MAdapter mAdapter;
	public static List<LinkmanModel> dataCount;
	public static List<LinkmanModel> data;

	int preCount = 0;
	
	private static boolean isBumen = true;
	
	@Override
	public void initUI() {
		setContentView(R.layout.linkman);

		this.findViewById(R.id.lm_search_btn).setOnClickListener(this);
		this.findViewById(R.id.lm_btn_cancel).setOnClickListener(this);
		this.findViewById(R.id.lm_btn_per).setOnClickListener(this);
		mPullList = (PullToRefreshListView) this.findViewById(R.id.lm_list);
		mPullList.setMode(PullToRefreshListView.MODE_PULL_DOWN_TO_REFRESH);
		mPullList.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				buildRequestGetLinkman();
			}
		});
		mList = mPullList.getRefreshableView();
		mProgress = (ProgressBar) this.findViewById(R.id.lm_progress);
		mEdit = (EditText) this.findViewById(R.id.lm_search_edit);
		mRadio = (RadioGroup) this.findViewById(R.id.lm_xzyh_group);

		if (data == null) {
			data = new ArrayList<LinkmanModel>();
		}
		if(dataCount == null) {
			dataCount = new ArrayList<LinkmanModel>();
		}
		
		mAdapter = new MAdapter();

		mList.setAdapter(mAdapter);
		
		mEdit.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				Log.e("", "onTextChanged:" + preCount + "  " + s.length());
				if (preCount > s.length() || preCount == 0) {
					filterData(s.toString(), true);
				} else {
					filterData(s.toString(), false);
				}
				preCount = s.length();
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		mList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (!data.get(arg2).isBumen) {
					data.get(arg2).isChecked = !data.get(arg2).isChecked;
				} else {
					data.get(arg2).isChecked = !data.get(arg2).isChecked;
					String str = data.get(arg2).name;
					for (int i = 0; i < data.size(); i++) {
						if (StringUtils.isNotEmpty(data.get(i).buMen) && data.get(i).buMen.equals(str)) {
							data.get(i).isChecked = data.get(arg2).isChecked;
						}
					}
				}
				mAdapter.notifyDataSetChanged();
			}
		});
		
		mRadio.check(isBumen ? R.id.lm_xzyh_group_radio1 : R.id.lm_xzyh_group_radio2);
		
		mRadio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				doChangeType();
				isBumen = (checkedId == R.id.lm_xzyh_group_radio1);
			}
		});
		super.initUI();
	}

	private void doChangeType() {
		mEdit.setText("");
		if (LinkmanRequest.users != null) {
			LinkmanRequest.users.clear();
		}
		if (data != null) {
			data.clear();
		}
		mAdapter.notifyDataSetChanged();
		initData();
	}
	
	@Override
	public void initData() {
//		if (LinkmanRequest.users != null) {
//			LinkmanRequest.users.clear();
//		}
		if (task != null) {
			task.cancel(true);
		}
		if (LinkmanRequest.users == null || LinkmanRequest.users.size() <= 0) {
			if(LinkmanRequest.isCache(this, isBumen())) {
				doParseCache();
			} else {
				buildRequestGetLinkman();
			}
		} else {
			initCenterUI(true);
			if (data != null && data.size() > 0) {
				if(mAdapter != null) {
					mAdapter.notifyDataSetChanged();
				}
				return;
			}
			convertData();
			mAdapter.notifyDataSetChanged();
		}
		super.initData();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.lm_search_btn:
			filterData(mEdit.getText().toString().trim(), true);
			break;
		case R.id.lm_btn_cancel:
			finish();
			break;
		case R.id.lm_btn_per:
			doResult();
			break;
		default:
			break;
		}
	}

	private void doParseCache() {
		initCenterUI(false);
		new AsyncTask<String, String, String> () {
			@Override
			protected String doInBackground(String... params) {
				LinkmanRequest.parseCacheData(LinkmanActivity.this, isBumen());
				return null;
			}
			
			@Override
			protected void onPostExecute(String result) {
				initCenterUI(true);
				convertData();
				mAdapter.notifyDataSetChanged();
				super.onPostExecute(result);
			}
			
		}.execute("");
	}
	
	private void doResult() {
		String names = "";
		String ids = "";
		for (int i = 0; i < data.size(); i++) {
			if (!data.get(i).isBumen && data.get(i).isChecked) {
				names = names + data.get(i).name + ",";
				ids = ids + data.get(i).id + ",";
			}
		}
		if (StringUtils.isEmpty(names) || StringUtils.isEmpty(ids)) {
			showToast("您还没有选择联系人");
		} else {
			names = names.substring(0, names.length() - 1);
			ids = ids.substring(0, ids.length() - 1);
			Intent intent = new Intent();
			intent.putExtra("name", names);
			intent.putExtra("id", ids);
			setResult(RESULT_OK, intent);
			finish();
		}
	}

	int t = 0;
	
	private void convertData() {
		if (LinkmanRequest.users != null) {
			t = 0;
			dataCount.clear();
			data.clear();
			for (int i = 0; i < LinkmanRequest.users.size(); i++) {
				LinkmanModel lm = new LinkmanModel();
				lm.name = LinkmanRequest.users.get(i).get(0).buMen;
				lm.isBumen = true;
				data.add(lm);
				dataCount.add(lm);
				for (int j = 0; j < LinkmanRequest.users.get(i).size(); j++) {
					t ++;
					LinkmanModel lmm = LinkmanRequest.users.get(i).get(j);
					lmm.isChecked = false;
					data.add(lmm);
					dataCount.add(lmm);
				}
			}
			Log.e("", "t:" + t + "  LinkmanRequest.users.size():" + LinkmanRequest.users.size());
		}
	}
	
	private void filterData(String keys, boolean isNew) {
		if (isNew) {
			filterDataFromNewData(keys);
		} else {
			filterDataFromOldData(keys);
		}
	}
	
	private void filterDataFromOldData(String keys) {
		
		if (data != null && keys != null) {
			if (keys.equals("")) {
				data.clear();
				data.addAll(dataCount);
				mAdapter.notifyDataSetChanged();
				return;
			}
			List<LinkmanModel> d = new ArrayList<LinkmanModel>();
			char[] ks = keys.toLowerCase().toCharArray();
			for (int j = 0; j < data.size(); j++) {
				data.get(j).isChecked = false;
				if (data.get(j).isBumen) {
					d.add(data.get(j));
					continue;
				}
				if (ks.length > data.get(j).py.length) {
					Log.e("", "continue:" + data.get(j));
					continue;
				}
				int indexPy = 0;
				int indexName = 0;
				int succPy = 0;
				int succName = 0;
				for (int i = 0; i < ks.length; i++) {
					for (int j2 = indexPy; j2 < data.get(j).py.length; j2++) {
						Log.e("", "indexPy:" + indexPy + " ks[i]:" + ks[i] + " py[j2]:" + data.get(j).py[j2]);
						indexPy ++;
						if (ks[i] == data.get(j).py[j2]) {
							indexPy = j2 + 1;
							succPy ++;
							break;
						}
					}
					Log.e("", "succPy:" + succPy + " ks.length:" + ks.length);
					if (succPy == ks.length) {
						break;
					}
					char[] names = data.get(j).name.toCharArray();
					for (int j2 = indexName; j2 < names.length; j2++) {
						indexName ++;
						if (ks[i] == names[j2]) {
							indexName = j2 + 1;
							succName ++;
							break;
						}
					}
					if (succName == ks.length) {
						break;
					}
				}
				if (succPy == ks.length || succName == ks.length) {
					d.add(data.get(j));
				}
			}
			for (int i = 0; i < d.size(); i++) {
				if (((i + 1) >= d.size() && (d.get(i).isBumen)) || (d.get(i).isBumen && d.get(i + 1).isBumen)) {
					d.remove(i);
					i = i - 1;
				}
			}
			data.clear();
			data.addAll(d);
			mAdapter.notifyDataSetChanged();
		}
	}
	
	private void filterDataFromNewData(String keys) {
		
		if (dataCount != null && keys != null) {
			if (keys.equals("")) {
				data.clear();
				data.addAll(dataCount);
				mAdapter.notifyDataSetChanged();
				return;
			}
			List<LinkmanModel> d = new ArrayList<LinkmanModel>();
			char[] ks = keys.toLowerCase().toCharArray();
			for (int j = 0; j < dataCount.size(); j++) {
				dataCount.get(j).isChecked = false;
				if (dataCount.get(j).isBumen) {
					d.add(dataCount.get(j));
					mAdapter.notifyDataSetChanged();
					continue;
				}
				if (ks.length > dataCount.get(j).py.length) {
					continue;
				}
				int indexPy = 0;
				int indexName = 0;
				int succPy = 0;
				int succName = 0;
				for (int i = 0; i < ks.length; i++) {
					for (int j2 = indexPy; j2 < dataCount.get(j).py.length; j2++) {
						indexPy ++;
						if (ks[i] == dataCount.get(j).py[j2]) {
							indexPy = j2 + 1;
							succPy ++;
							break;
						}
					}
					char[] names = dataCount.get(j).name.toCharArray();
					for (int j2 = indexName; j2 < names.length; j2++) {
						indexName ++;
						if (ks[i] == names[j2]) {
							indexName = j2 + 1;
							succName ++;
							break;
						}
					}
				}
				if (succPy == ks.length || succName == ks.length) {
					d.add(dataCount.get(j));
					mAdapter.notifyDataSetChanged();
				}
			}
			for (int i = 0; i < d.size(); i++) {
				if ((i + 1) >= d.size() || d.get(i).isBumen && d.get(i + 1).isBumen) {
					d.remove(i);
					i = i - 1;
				}
			}
			data.clear();
			data.addAll(d);
			mAdapter.notifyDataSetChanged();
		}
	}
	
	protected void buildRequestGetLinkman() {
		initCenterUI(false);
		mPullList.showHeadView();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		netRequestGetLinkman(new LinkmanRequest(params, this, isBumen()));
	}

	WcfAsyncTask task;
	
	private void netRequestGetLinkman(AbstractRequest request) {
		if (task != null) {
			task.cancel(true);
		}
		task = new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				initCenterUI(true);
				mPullList.onRefreshComplete();
//				if (isBumen()) {
					if (LinkmanRequest.users != null) {
						convertData();
						mAdapter.notifyDataSetChanged();
					}
//				} else {
//					
//				}
			}

			@Override
			public void onCancel() {
				mPullList.onRefreshComplete();
				initCenterUI(true);
			}

			@Override
			public void onProgress(int progress, String msg) {
				LinkmanActivity.this.showToast(msg);
			}
		});
		task.execute(request);
	}

	private boolean isBumen() {
		return mRadio.getCheckedRadioButtonId() == R.id.lm_xzyh_group_radio1;
	}
	
	private void initCenterUI(boolean isShowList) {
		if (isShowList) {
			if (mList.getVisibility() != View.VISIBLE) {
				mList.setVisibility(View.VISIBLE);
			}
			if (mProgress.getVisibility() != View.INVISIBLE) {
				mProgress.setVisibility(View.INVISIBLE);
			}
		} else {
			if (mList.getVisibility() != View.INVISIBLE) {
				mList.setVisibility(View.INVISIBLE);
			}
			if (mProgress.getVisibility() != View.VISIBLE) {
				mProgress.setVisibility(View.VISIBLE);
			}
		}
	}

	private class MAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (data.get(position).isBumen) {
				return getBumenView(position, convertView, parent);
			} else {
				return getLinkmanView(position, convertView, parent);
			}
		}

		public View getLinkmanView(int position, View convertView,
				ViewGroup parent) {
			Holder1 holder;
			if (convertView == null
					|| !(convertView.getTag() instanceof Holder1)) {
				convertView = getLayoutInflater().inflate(
						R.layout.linkman_item1, null);
				holder = new Holder1();
				holder.img = (ImageView) convertView.findViewById(R.id.lmi_img);
				holder.name = (TextView) convertView.findViewById(R.id.lmi_txt);
				holder.check = (CheckBox) convertView.findViewById(R.id.lmi_check);
			} else {
				holder = (Holder1) convertView.getTag();
			}

			holder.name.setText(data.get(position).name);
			holder.check.setChecked(data.get(position).isChecked);
			return convertView;
		}

		public View getBumenView(int position, View convertView,
				ViewGroup parent) {
			Holder2 holder;
			if (convertView == null
					|| !(convertView.getTag() instanceof Holder2)) {
				convertView = getLayoutInflater().inflate(
						R.layout.linkman_item2, null);
				holder = new Holder2();
				holder.name = (TextView) convertView.findViewById(R.id.lmi_txt);
				holder.check = (CheckBox) convertView.findViewById(R.id.lmi_check);
			} else {
				holder = (Holder2) convertView.getTag();
			}
			holder.name.setText(data.get(position).name);
			holder.check.setChecked(data.get(position).isChecked);
			return convertView;
		}

	}

	private static final class Holder1 {
		@SuppressWarnings("unused")
		ImageView img;
		TextView name;
		CheckBox check;
	}

	private static final class Holder2 {
		TextView name;
		CheckBox check;
	}

}
